package com.mnb.base.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mnb.base.entity.SysRoleMenu;
import com.mnb.base.mapper.SysRoleMenuMapper;
import com.mnb.base.mapper.SysUserRoleMapper;
import com.mnb.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.mnb.base.mapper.SysRoleMapper;
import com.mnb.base.entity.SysRole;
import com.mnb.base.service.SysRoleService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public R getPageList(SysRole sysRole) {
        Page page = PageHelper.startPage(sysRole.getPageNum(), sysRole.getPageSize()).doSelectPage(() -> sysRoleMapper.getList(sysRole));
        R result = R.ok(page.getResult());
        result.setTotal(page.getTotal());
        return result;
    }

    @Override
    @Transactional
    public R insert(SysRole sysRole) {
        sysRole.setStatus("0");
        sysRoleMapper.insert(sysRole);
        insertRoleMenu(sysRole);
        return R.ok();
    }

    @Override
    @Transactional
    public R udpate(SysRole sysRole) {
        // 修改角色信息
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        // 删除角色与菜单关联
        sysRoleMenuMapper.deleteRoleMenuByRoleId(sysRole.getRoleId());
        insertRoleMenu(sysRole);
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            SysRole role = sysRoleMapper.selectByPrimaryKey(roleId);
            checkRoleAllowed(role);

            if (countUserRoleByRoleId(roleId) > 0) {
                throw new RuntimeException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        sysRoleMenuMapper.deleteRoleMenu(roleIds);
        sysRoleMapper.deleteRoleByIds(roleIds);
        return R.ok();
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    public void checkRoleAllowed(SysRole role) {
        if (!StringUtils.isEmpty(role.getRoleId()) && role.getRoleKey().equals("super-admin")) {
            throw new RuntimeException("不允许操作超级管理员角色");
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return sysUserRoleMapper.countUserRoleByRoleId(roleId);
    }

    @Override
    public R list(SysRole sysRole) {
        List<SysRole> list = sysRoleMapper.getList(sysRole);
        return R.ok(list);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Object userId) {
        List<SysRole> perms = sysRoleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (!StringUtils.isEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = sysRoleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

}
